<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      v-loading="formLoading"
      label-width="auto"
    >
      <el-tabs :stretch="false" table-center type="border-card">
        <el-tab-pane label="设置">
          <el-row>
            <el-col :span="24" :push="1">
              <el-form-item label="账号" prop="mailboxAccount">
                <el-input
                  v-model="formData.mailboxAccount"
                  placeholder="请输入账号"
                  :clearable="true"
                  @blur="accountBlur"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24" :push="1">
              <el-form-item label="密码" prop="mailboxPassword">
                <el-input
                  v-model="formData.mailboxPassword"
                  placeholder="请输入密码"
                  :clearable="true"
                  type="password"
                  autocomplete="new-password"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" :push="1">
              <el-form-item label="显示名称" prop="showName">
                <el-input
                  v-model="formData.showName"
                  placeholder="请输入显示名称"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" :push="1">
              <el-form-item label="发信名称" prop="sendName">
                <el-input
                  v-model="formData.sendName"
                  placeholder="请输入发信名称"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6" :push="3">
              <el-form-item label="定时收取邮件" prop="isTimeReceive">
                <el-checkbox v-model="formData.isTimeReceive" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="4">
              <el-form-item label="" prop="timeReceiveInterval">
                <div class="mr-2">每隔</div>
                <InputNumber
                  :min="3"
                  v-model="formData.timeReceiveInterval"
                  placeholder="请输入定时收取邮件间隔"
                  style="width: 50px !important"
                  class="mr-2"
                />
                <div>分钟</div>
              </el-form-item>
            </el-col>
            <el-row>
              <el-col :span="24" :push="1">
                <el-form-item label="拥有人" prop="ownerId">
                  <el-select v-model="formData.ownerId" placeholder="请输入拥有人">
                    <el-option
                      v-for="item in userList"
                      :key="item.id"
                      :label="item.nickname"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="服务器">
          <el-row>
            <el-col :span="24">
              <el-form-item label="邮箱类型" prop="mailboxProtocolType">
                <el-select v-model="formData.mailboxProtocolType" placeholder="请输入邮箱类型">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.MAILBOX_PROTOCOL)"
                    :key="dict.value.toString()"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="15">
              <el-form-item label="收件服务器" prop="receiveAddress">
                <el-input
                  v-model="formData.receiveAddress"
                  placeholder="请输入收件服务器"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="SSL" prop="isReceiveSecure" style="margin-left: -55px">
                <el-checkbox v-model="formData.isReceiveSecure" style="margin-left: -8px" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :pull="1">
              <el-form-item label="端口：" prop="receivePort">
                <InputNumber
                  v-model="formData.receivePort"
                  style="width: 60px; margin-left: -10px"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="15">
              <el-form-item label="发件服务器" prop="sendAddress">
                <el-input
                  v-model="formData.sendAddress"
                  placeholder="请输入发件服务器"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="SSL" prop="isSendSecure" style="margin-left: -55px">
                <el-checkbox v-model="formData.isSendSecure" style="margin-left: -8px" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :pull="1">
              <el-form-item label="端口：" prop="sendPort">
                <InputNumber v-model="formData.sendPort" style="width: 60px; margin-left: -10px" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="" prop="isStarttls">
                <el-checkbox v-model="formData.isStarttls" :disabled="formData.disableStarttls"
                  >如服务器支持，用STARTTLS加密传输</el-checkbox
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="MailboxAccountEdit" lang="ts">
import * as AccountApi from '@/api/mailbox/mailboxAccount'
import * as AccountModel from '@/model/mailbox/account/MailboxAccount'
import { MailboxProtocolEnum } from '@/utils/constants'
import * as UserApi from '@/api/system/user/user'
import { useUserStore } from '@/store/modules/user'
import { isEmpty } from 'lodash-es'
import { mailboxAccountTypeDetail } from '@/views/mailbox/mailboxAccount/MailboxAccountTypeDetail'
import InputNumber from '@/components/InputNumber/src/InputNumber.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import type { FormRules } from 'element-plus'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
let formType = ''
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const userStore = useUserStore()
const formData = ref({
  mailboxAccount: '',
  mailboxPassword: '',
  showName: '',
  sendName: '',
  isTimeReceive: true,
  timeReceiveInterval: 15,
  mailboxProtocolType: MailboxProtocolEnum.IMAP,
  receiveAddress: '',
  isReceiveSecure: true,
  receivePort: 0,
  sendAddress: '',
  isSendSecure: true,
  sendPort: 0,
  isStarttls: false,
  disableStarttls: false,
  ownerId: userStore.getUser.id
})
interface RuleForm {
  mailboxAccount: string
  mailboxPassword: string
  ownerId: string
}
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const formRules = reactive<FormRules<RuleForm>>({
  mailboxAccount: [
    { required: true, message: '账号不能为空', trigger: 'change' },
    { type: 'email', message: '请输入正确的邮箱账号', trigger: 'blur' }
  ],
  mailboxPassword: [{ required: true, message: '密码不能为空', trigger: 'change' }],
  ownerId: [{ required: true, message: '拥有人不能为空', trigger: 'blur' }]
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  // 获得用户列表
  userList.value = await UserApi.getOwnerUser()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AccountApi.singleGet(id)
      loadDisableStarttls()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    mailboxAccount: '',
    mailboxPassword: '',
    showName: '',
    sendName: '',
    isTimeReceive: true,
    timeReceiveInterval: 15,
    mailboxProtocolType: MailboxProtocolEnum.IMAP,
    receiveAddress: '',
    isReceiveSecure: true,
    receivePort: 0,
    sendAddress: '',
    isSendSecure: true,
    sendPort: 0,
    isStarttls: false,
    disableStarttls: false,
    ownerId: userStore.getUser.id
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (isEmpty(formData.value.receiveAddress)) {
    await message.confirm('收件服务器为空，是否继续？')
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AccountModel.MailboxAccount
    let accountId = 0
    if (formType === 'create') {
      accountId = await AccountApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await AccountApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success', accountId)
  } finally {
    formLoading.value = false
  }
}

const loadDisableStarttls = () => {
  const beginIndex = formData.value.mailboxAccount.indexOf('@')
  if (beginIndex < 0) return
  const endIndex = formData.value.mailboxAccount.indexOf('.')
  if (endIndex < 0) return
  const mailboxType = formData.value.mailboxAccount.slice(beginIndex + 1)
  if (mailboxAccountTypeDetail[mailboxType] == null) return
  formData.value.disableStarttls = mailboxAccountTypeDetail[mailboxType].disableStarttls
}

const accountBlur = () => {
  formData.value.mailboxAccount = formData.value.mailboxAccount.trim()
  formData.value.showName = ''
  formData.value.sendName = ''
  const beginIndex = formData.value.mailboxAccount.indexOf('@')
  if (beginIndex < 0) return
  const endIndex = formData.value.mailboxAccount.indexOf('.')
  if (endIndex < 0) return
  const mailboxName = formData.value.mailboxAccount.slice(0, beginIndex)
  const mailboxType = formData.value.mailboxAccount.slice(beginIndex + 1)
  if (isEmpty(mailboxType)) return
  formData.value.sendName = formData.value.mailboxAccount
  formData.value.showName =
    formData.value.mailboxAccount.slice(beginIndex + 1, endIndex) + '(' + mailboxName + ')'
  if (mailboxAccountTypeDetail[mailboxType] == null) return
  formData.value = { ...formData.value, ...mailboxAccountTypeDetail[mailboxType] }
}
</script>
<style>
[table-center] .el-tabs__header {
  display: flex;
  justify-content: center;
}
</style>
